Answer:

The output is:

0 1 2 3 4 5
sum is 15

Top-driven Loop

Here is the example for loop and its equivalent while loop:

for loop   while loop
int count, sum;

sum = 0;
for ( count = 0; count <= 5; count++ )
{
  sum = sum + count ;
  System.out.print( count + " " );
}
System.out.println( "sum is: " + sum );
 
int count, sum;
sum   = 0;
count = 0;
while ( count <= 5 )
{
  sum = sum + count ;
  System.out.print( count + " " );
  count++ ;
}
System.out.println( "sum is: " + sum );

Notice two important aspects of these loops:

  1. The test is performed just before execution is about to (re-)enter the loop body.
  2. The change is performed at the bottom of the loop body, just before the test is re-evaluated.

Loops that work this way are called top-driven loops, and are usually mentally easier to deal with than other arrangements. Look back at the loop flow chart to see this graphically.

QUESTION 5:

Where should the initialization part of a loop be located in order to make it mentally easy to deal with?